﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Reply : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckIP()) return;
        doit();
    }

    void doit()
    {
        if (String.IsNullOrEmpty(UserName) || String.IsNullOrEmpty(Content))
        {
            Response.Write("昵称和评论内容不能为空！");
            return;
        }

        int id = 0;
        String ids = Request.QueryString["ID"];
        if (!String.IsNullOrEmpty(ids)) int.TryParse(ids, out id);
        XCMSData.Title title = XCMSData.Title.FindByKey(id);
        if (title == null)
        {
            Response.Write("非法参数！");
            return;
        }

        XCMSData.Reply reply = new XCMSData.Reply();
        reply.TitleID = title.ID;
        reply.UserID = 0;
        reply.UserName = UserName;
        reply.PostTime = DateTime.Now;
        reply.IP = IP;
        reply.Content = Content;
        reply.Insert();

        Response.Redirect("Article.aspx?ID=" + id.ToString());
    }

    Boolean CheckIP()
    {
        String key = "Reply_IP_" + IP;
        int count = 0;
        if (Cache[key] != null)
        {
            int.TryParse(Cache[key].ToString(), out count);
        }
        count++;
        if (count > 3)
        {
            Response.Write("请不要频繁发布评论！");
            Response.End();
            return false;
        }
        if (Cache[key] != null)
            Cache[key] = count;
        else
            Cache.Insert(key, count, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10));
        return true;
    }

    public String IP
    {
        get
        {
            return Request.UserHostAddress;
        }
    }

    public String UserName
    {
        get
        {
            if (Request["UserName"] == null) return null;
            return Request["UserName"].ToString();
        }
    }

    public String Content
    {
        get
        {
            if (Request["Content"] == null) return null;
            return Request["Content"].ToString();
        }
    }
}
